package com.bxl.netty.rpc.common.serialize;



import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * <>
 *
 * @author baixl
 * @date 2021/2/24
 */
public class KryoSerialize implements Serialize {
    /**Kryo对象线程不安全，但是能加快序列化和反序列的速度*/
    private static  final ThreadLocal<Kryo> serials = new ThreadLocal<Kryo>() {
        protected Kryo initialValue() {
            Kryo kryo = new Kryo();
            kryo.setRegistrationRequired(false);
            return kryo;
        }
    };

    public  byte[] serialize(Object obj) {
        Kryo kryo= serials.get();
        //2.1构建流对象(Java中默认是使用ObjectOutputStream)
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        Output output=new Output(bos);
        try {
            //2.2对象序列化
            kryo.writeClassAndObject(output, obj);
        } finally {
            //2.3释放资源
            output.close();
        }
       
        return bos.toByteArray();
    }
	
    public  <T> T  deserialize(byte[] array) {
        Kryo kryo= serials.get();
        //2.1构建流对象
        Input input=new Input(new ByteArrayInputStream(array));
        Object obj;
        try {
            //2.2对象反序列化
            obj = kryo.readClassAndObject(input);
        } finally {
            //2.3释放资源
            input.close();
        }
        return (T)obj;
    }
}
